import React from 'react';
import { messages } from 'share/common';
import { connect } from 'react-redux';
import {
  Spin, Radio, message, Modal, Button, Row, Col, Slider, Tooltip
} from 'antd';
import consumerService from '../consumer.service';
import SyncData from 'containers/supplier-management/overview/supplier-detail/sync-data';
import 'styles/supplier-management/new-consumer-management/settings/cmbc-setting.scss';
import Condition from 'components/condition';
import swapImg from 'images/swap.png';

const { If } = Condition;

class CMBCSetting extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      okLoading: false,
      saveLoading: false,
      modalVisible: false,
      modalOkDisabled: true,
      info: {},
      tooltipVisible: false,
    };
  }

  // 修改商务卡消费记录属性
  handleConsumeTypeChange = (e) => {
    const { info } = this.state;
    if (e.target.value === 1003) {
      info.paymentType = 1002;
      info.activateDate = `${new Date().getFullYear()}06`;
    } else {
      info.paymentType = e.target.value;
      info.activateDate = null;
    }
    this.setState({ info });
  };

  componentDidMount() {
    this.setState({ loading: true });
    consumerService.getCMBCAccount()
      .then((res) => {
        this.setState({
          loading: false,
          billEnabled: res.data.rows.billEnabled,
          info: res.data.rows || {}
        }, () => {
          // 防止tooltip定位不准确
          setTimeout(() => {
            this.setState({ tooltipVisible: true });
          }, 200);
        });
      });
  }

  handleModelTypeChange = (e) => {
    this.setState({ billEnabled: e.target.value });
  };

  handleLastSubmit = (flag) => {
    flag && window.open('/main/supplier/consumer-card-list/consumer-open-page/CMBC/2');
  };

  handleSyncData = () => {
    if (this.syncDataRef && this.syncDataRef.state && this.syncDataRef.state.dataStatusChange) {
      this.syncDataRef.getList();
      this.syncDataRef.setState({
        data: [], dataStatusChange: false, selectedRowKeys: [], selectedRows: []
      });
      this.setState({ modalOkDisabled: true });
    }
    this.setState({ modalVisible: true });
  };

  handleModalOK = () => {
    this.syncDataRef.confirmSyncData();
  };

  handleModalCancel = () => {
    this.setState({ modalVisible: false });
  };

  activeDateMarks = () => {
    const marks = {};
    for (let i = 1; i <= 12; i++) {
      marks[i] = i;
    }
    return marks;
  };

  tipFormatter = () => {
    // paymentType: activateDate时间后的支付类型
    const { info: { paymentType, activateDate } } = this.state;
    const handleSwap = () => {
      const { info } = this.state;
      if (info.paymentType === 1001) {
        info.paymentType = 1002;
      } else {
        info.paymentType = 1001;
      }
      this.setState({ info });
    };
    return (
      <div>
        {messages('supplier.key940', {arg1: +activateDate.slice(4, 6)})/* {arg1}月前 */}
        {paymentType === 1002 ? messages('supplier.key478')/* 个人支付 */ : messages('supplier.key479')/* 公司支付 */}
        <img
          alt=""
          src={swapImg}
          style={{
            width: 36, margin: '0 5px', position: 'relative', top: -2, cursor: 'pointer'
          }}
          onClick={handleSwap}
        />
        {messages('supplier.key941', {arg1: +activateDate.slice(4, 6)})/* {arg1}月后 */}
        {paymentType === 1001 ? messages('supplier.key478')/* 个人支付 */ : messages('supplier.key479')/* 公司支付 */}
        （
        {messages('supplier.key942')/* 含当月 */}
        ）
      </div>
    );
  };

  handleBillMonthChange = (value) => {
    const { info } = this.state;
    const year = info.activateDate.slice(0, 4);
    info.activateDate = `${year}${value > 9 ? value : `0${value}`}`;
    this.setState({ info });
  }

  handleSave = () => {
    const { info, billEnabled } = this.state;
    const params = {
      billEnabled,
      paymentType: info.paymentType,
      activateDate: info.activateDate,
    };
    this.setState({ saveLoading: true });
    consumerService.setCardBillEnable('CMBC', params).then(() => {
      message.success(messages('common.operate.success'));
    }).finally(() => {
      this.setState({ saveLoading: false });
    });
  };

  getToolTipStyle = (type) => {
    const { info } = this.state;
    const value = info.activateDate && +info.activateDate.slice(4, 6);
    if (type === 'placement') {
      return (
        value >= 9 ? 'topRight'
          : value <= 4 ? 'topLeft' : 'top'
      );
    }
    if (type === 'overlayStyle') {
      return (
        value >= 9 ? { right: 44 * (12 - value) - 16 }
          : value <= 4 ? { left: 44 * (value - 1) - 16 } : { left: 44 * (value - 1) - 3 }
      );
    }
  };

  render() {
    const {
      loading, okLoading, saveLoading, modalVisible, modalOkDisabled, billEnabled, info, tooltipVisible
    } = this.state;
    return (
      <div className="cmbc-setting">
        <Spin spinning={loading}>
          <div className="consumer-other-setting-card-container">
            <h3>{messages('supplier.key651')/* 消费记录属性 */}</h3>
            <div>
              1.
              {' '}
              {messages('supplier.key943')/* 商务卡消费记录属性设置 */}
            </div>
            <div>{messages('supplier.key480')/* 说明：当商务卡消费记录属性="公司支付"时，所有关联商务卡消费记录的费用会是公司支付 */}</div>
            <Row>
              <Col span={4}>
                {messages('supplier.key75')/* 支付方式 */}
                ：
              </Col>
              <Col span={20}>
                <Radio.Group
                  value={info.activateDate ? 1003 : info.paymentType || 1001}
                  onChange={this.handleConsumeTypeChange}
                >
                  <Radio value={1001}>{messages('supplier.key949')/* 全部个人支付 */}</Radio>
                  <Radio value={1002}>{messages('supplier.key950')/* 全部公司支付 */}</Radio>
                  <Radio value={1003}>{messages('supplier.key944')/* 按账单月设置公司／个人支付 */}</Radio>
                </Radio.Group>
              </Col>
            </Row>
            {info.activateDate && (
              <Row className="consumer-other-setting-card-container-mouth-setting">
                <Col span={4}>
                  {messages('supplier.key945')/* 账单月时间 */}
                  ：
                </Col>
                <Col span={14} className="consumer-other-setting-card-container-month">
                  <Tooltip
                    visible={tooltipVisible}
                    title={this.tipFormatter()}
                    placement={this.getToolTipStyle('placement')}
                    overlayClassName="consumer-other-setting-card-container-month-tooltip"
                    getPopupContainer={() => document.getElementsByClassName('cmbc-setting')[0]}
                  >
                    <div
                      className="consumer-other-setting-card-container-month-center"
                      style={this.getToolTipStyle('overlayStyle')}
                    />
                  </Tooltip>
                  <Slider
                    min={1}
                    max={12}
                    step={null}
                    tipFormatter={null}
                    marks={this.activeDateMarks()}
                    defaultValue={+info.activateDate.slice(4, 6)}
                    onChange={this.handleBillMonthChange}
                  />
                </Col>
                <Col span={2} className="consumer-other-setting-card-container-year">
                  {info.activateDate.slice(0, 4)}
                  {messages('supplier.key946')/* 年 */}
                </Col>
              </Row>
            )}
            <If value={info.paymentType === 1002 || info.activateDate}>
              <Row>
                <Col span={4}>
                  {info.activateDate ? messages('supplier.key947')/* 公司设置模式设置 */ : messages('supplier.key948')/* 设置模式 */}
                  ：
                </Col>
                <Col span={20}>
                  <Radio.Group
                    value={billEnabled}
                    onChange={this.handleModelTypeChange}
                  >
                    <Radio value={1} style={{ marginBottom: 8 }}>
                      {messages('supplier.key859')/* 根据消费记录自动为员工创建借款单 */}
                    </Radio>
                    {' '}
                    <br />
                    <Radio value={0}>{messages('supplier.key860')/* 推送消费记录明细供员工提交报销单 */}</Radio>
                  </Radio.Group>
                </Col>
              </Row>
            </If>
          </div>
        </Spin>
        <div className="consumer-other-setting-card-container">
          <h3>{messages('supplier.key652')/* 消费记录同步 */}</h3>
          <div>
            {messages('supplier.key296')/* 点击 */}
&nbsp;
            <a onClick={this.handleSyncData}>
              【
              {messages('supplier.key102'/* 同步消费数据 */)}
              】
            </a>
&nbsp;
            {messages('supplier.key654')/* 可同步员工消费记录 */}
          </div>
        </div>
        <Modal
          title={messages('supplier.key102'/* 同步消费数据 */)}
          visible={modalVisible}
          width={800}
          className="list-selector"
          onCancel={this.handleModalCancel}
          footer={[
            <Button key="back" onClick={this.handleModalCancel}>{messages('common.back')/* 返回 */}</Button>,
            <Button
              key="submit"
              type="primary"
              loading={okLoading}
              disabled={modalOkDisabled}
              onClick={this.handleModalOK}
            >
              {messages('supplier.key103'/* 确认 */)}
            </Button>,
          ]}
        >
          <SyncData
            supplierName="CMBC"
            wrappedComponentRef={(inst) => this.syncDataRef = inst}
            handleModalCancel={this.handleModalCancel}
            checkUserIsConfirm={modalOkDisabled => this.setState({ modalOkDisabled })}
            showModal={modalVisible}
          />
        </Modal>
        <Button type="primary" loading={saveLoading} onClick={this.handleSave}>
          {messages('common.save')}
        </Button>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
  };
}

export default connect(mapStateToProps)(CMBCSetting);
